package me.tuyou.maven.plugin;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

@Mojo(name = "lineCount", defaultPhase = LifecyclePhase.COMPILE)
public class CountMojo extends AbstractMojo {

    @Parameter(defaultValue = "${project.build.sourceDirectory}")
    private String sourceDirectory;

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        getLog().info("source directory:" + sourceDirectory);

        File file = new File(sourceDirectory);
        try {
            int count = count(file);
            getLog().info("total row count:" + count);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    private int count(File file) throws FileNotFoundException {
        int count = 0;
        if (file.isDirectory()) {
            for (File listFile : file.listFiles()) {
                count += count(listFile);
            }
        } else {
            BufferedReader reader = new BufferedReader(new FileReader(file));
            count += reader.lines().count();
        }
        return count;
    }
}